var directiveModule = angular.module('app-directive', []);
directiveModule.directive('uploadImage', function () {
    return {
        require: 'ngModel',
        scope: {uploadId: '@'},
        link: function (scope, elem, attrs, _ngmodel) {
            var bucketDomain = "http://o71tin5mf.bkt.clouddn.com/"
            //监控
            var watch = scope.$watch('uploadId', function (newValue, oldValue, scope) {
                var Qiniu = new QiniuJsSDK();
                var icon = Qiniu.uploader({
                    runtimes: 'html5,flash,html4',      // 上传模式,依次退化
                    browse_button: scope.uploadId,
                    uptoken_url: "/upload/token",
                    get_new_uptoken: false,
                    unique_names: true,
                    domain: bucketDomain,
                    auto_start: true,
                    filters: {
                        max_file_size: "5mb",//文件大小
                        prevent_duplicates: false,
                        // Specify what files to browse for
                        mime_types: [
                            {title: "Image files", extensions: "jpg,gif,png,jpeg"}, // 限定jpg,gif,png后缀上传
                        ]
                    },
                    init: {
                        'BeforeUpload': function (up, files) {
                            //return checksize(files[0]);
                        },
                        'FileUploaded': function (up, file, info) {
                            var data = $.parseJSON(info);
                            _ngmodel.$setViewValue(data.key);
                            elem.find("img").attr("src", bucketDomain + data.key);
                            scope.$apply();
                        },
                        'Error': function (up, file, info) {
                            alert("图片格式不正确")
                        }
                    }
                });
                watch();
            });

            /**
             * 绑定数据更新时触发
             */
            _ngmodel.$render = function () {
                if (_ngmodel.$viewValue == null || typeof(_ngmodel.$viewValue) == "undefined"||_ngmodel.$viewValue == ""){
                    elem.find("img").attr("src", _ngmodel.$viewValue);
                    return;
                } else {
                    elem.find("img").attr("src", bucketDomain + _ngmodel.$viewValue);
                }
            };
        }
    }
});

//阿里上传
directiveModule.directive('aliUpload',function(){
  return {
    require: 'ngModel',
    scope:{
      uploadFile:'@'
    },
    link:function(scope, elem, attrs, _ngmodel){
      _ngmodel.$render = function () {
          if (_ngmodel.$viewValue != null && typeof(_ngmodel.$viewValue) != "undefined"&&_ngmodel.$viewValue != ""){
              elem.find("img").attr("src",DOMAIN+_ngmodel.$viewValue).attr("style","width:350px;height:150px;");
          }
      };

      var DOMAIN = "http://sytp.oss-cn-shanghai.aliyuncs.com/";
      //上传对象
      var UP_CLIENT = new OSS.Wrapper({
        region: 'oss-cn-shanghai',
        accessKeyId:'LTAI2dzL7RJco9hV',
        accessKeySecret:'DbiNZEc8ndC5YgTqte6ddqVBZorVm9',
        bucket: 'sytp'
      });
      elem.change(function(){
        console.log(scope.uploadFile);
        var file = $("#"+scope.uploadFile).get(0).files[0];
        var name_ext =  file.name.split('.').pop();
        var storeAs = GUID()+"."+name_ext;
        UP_CLIENT.multipartUpload(storeAs, file).then(function (result) {
            _ngmodel.$setViewValue(result.name);
            elem.find("img").attr("src",DOMAIN+result.name).attr("style","width:350px;height:150px;");
        }).catch(function (err) {
            console.log(err);
        });
      })
    }
  }
});

//app上传
directiveModule.directive('aliUploadApp',function(){
    return {
        require: 'ngModel',
        scope:{
            uploadFile:'@'
        },
        link:function(scope, elem, attrs, _ngmodel){
            _ngmodel.$render = function () {
                if (_ngmodel.$viewValue != null && typeof(_ngmodel.$viewValue) != "undefined"&&_ngmodel.$viewValue != ""){
                    elem.find("img").attr("src",DOMAIN+_ngmodel.$viewValue).attr("style","width:350px;height:150px;");
                }
            };

            var DOMAIN = "http://sytp.oss-cn-shanghai.aliyuncs.com/";
            //上传对象
            var UP_CLIENT = new OSS.Wrapper({
                region: 'oss-cn-shanghai',
                accessKeyId:'LTAI2dzL7RJco9hV',
                accessKeySecret:'DbiNZEc8ndC5YgTqte6ddqVBZorVm9',
                bucket: 'sytp'
            });
            elem.change(function(){
                console.log(scope.uploadFile);
                var file = $("#"+scope.uploadFile).get(0).files[0];
                var name_ext =  file.name.split('.').pop();
                var storeAs = GUID()+"."+name_ext;
                UP_CLIENT.multipartUpload(storeAs, file).then(function (result) {
                    _ngmodel.$setViewValue(result.name);
                    elem.find("span").html("上传成功");
                }).catch(function (err) {
                    console.log(err);
                });
            })
        }
    }
});

//时间插件
directiveModule.directive('dateTimePicker',function(){
  return {
    require: 'ngModel',
    scope:{
      format:"@"
    },
    link:function(scope, elem, attrs, _ngmodel){
      elem.datetimepicker({
                   format: scope.format,
                   language: scope.language,
                   useCurrent: true
               })
       //点击事件
       elem.on('blur', function () {

                 console.info('this', this);
                 console.info('scope', scope);
                 console.info('attrs', attrs);
                 _ngmodel.$setViewValue(elem.val());
         });

    }
  }
})

//wangEditor富文本编辑器
directiveModule.directive("wangEditor",function(){
  return {
    require: 'ngModel',
    link:function(scope, elem, attrs, _ngmodel){
      var editor = new wangEditor(elem);
      editor.config.customUpload = true;  // 设置自定义上传的开关
      editor.config.customUploadInit = uploadInit;
      editor.create();
       /**
        * 绑定数据更新时触发
        */
       _ngmodel.$render = function () {
           if (_ngmodel.$viewValue == null || typeof(_ngmodel.$viewValue) == "undefined"||_ngmodel.$viewValue == ""){
               return;
           } else {
               editor.$txt.html(_ngmodel.$viewValue);
           }
       };
       //同步数据到ngModel中
       editor.onchange = function () {
        // 编辑区域内容变化时，实时打印出当前内容
        var html = this.$txt.html()
        _ngmodel.$setViewValue(html);
    };
    }
  }
})

directiveModule.directive('htmlShow',function(){
  return {
      require: 'ngModel',
      restrict:'E',
      link:function(scope, elem, attrs, _ngmodel){
        _ngmodel.$render = function () {
            if (_ngmodel.$viewValue == null || typeof(_ngmodel.$viewValue) == "undefined"||_ngmodel.$viewValue == ""){
                return;
            } else {
                elem.html(_ngmodel.$viewValue);
            }
        };
      }
  }
})


//时间插件
directiveModule.directive('imgPath',function(){
  return {
    require: 'ngModel',
    link:function(scope, elem, attrs, _ngmodel){
      var DOMAIN = "http://sytp.oss-cn-shanghai.aliyuncs.com/";
      _ngmodel.$render = function () {
          if (_ngmodel.$viewValue == null || typeof(_ngmodel.$viewValue) == "undefined"||_ngmodel.$viewValue == ""){
              return;
          } else {
              elem.attr("src",DOMAIN+_ngmodel.$viewValue)
          }
      };
    }
  }
})

/**
 * 生成UUID的方法
**/
function GUID() {
    return s4() + s4() + '' + s4() + '' + s4() + '' + s4() + '' + s4() + s4() + s4();
};
function s4() {
    return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
};

function uploadInit(){

    // this 即 editor 对象
  var editor = this;
  // 触发选择文件的按钮的id
  var btnId = editor.customUploadBtnId;
  // 触发选择文件的按钮的父容器的id
  var containerId = editor.customUploadContainerId;
  var DOMAIN = "http://sytp.oss-cn-shanghai.aliyuncs.com/";
  //上传对象
  var UP_CLIENT = new OSS.Wrapper({
    region: 'oss-cn-shanghai',
    accessKeyId:'LTAI2dzL7RJco9hV',
    accessKeySecret:'DbiNZEc8ndC5YgTqte6ddqVBZorVm9',
    bucket: 'sytp'
  });
  // 创建上传对象
  $("#"+btnId).change(function(){
      var file = $(this).find('input').get(0).files[0];
      var name_ext =  file.name.split('.').pop();
      var storeAs = GUID()+"."+name_ext;
      console.log(storeAs);
      UP_CLIENT.multipartUpload(storeAs, file).then(function (result) {
          console.log(result);
          //插入图片到editor
          editor.command(null, 'insertHtml', '<img src="' +  DOMAIN+result.name + '" style="max-width:370px;"/>')
      }).catch(function (err) {
          console.log(err);
      });

  });
}
